using MediatR;
using Microsoft.AspNetCore.Mvc;
using Medical.ErrorCode;
using BaseData.ErrorCode;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;

namespace Medical.WriteApi.Controllers
{
	/// <summary>
	/// 用户管理控制器（写操作）
	/// </summary>
	[ApiController]
	[Route("api/[controller]/[action]")]
	public class UserController : ControllerBase
	{
		private readonly IMediator _mediator;
		
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="mediator">MediatR中介者</param>
		public UserController(IMediator mediator)
		{
			_mediator = mediator;
		}

		/// <summary>
		/// 创建用户
		/// </summary>
		/// <param name="command">创建用户命令，包含用户名、密码、邮箱等信息</param>
		/// <returns>创建成功的用户信息</returns>
		/// <remarks>
		/// 示例请求:
		/// POST /api/User/CreateUser
		/// {
		///   "userName": "admin",
		///   "password": "123456",
		///   "email": "admin@example.com",
		///   "fullName": "管理员",
		///   "phone": "13800138000",
		///   "employeeId": 1,
		///   "isActive": true,
		///   "roleIds": [1, 2]
		/// }
		/// </remarks>
		/// <response code="200">创建成功，返回用户信息</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPost]
		[ProducesResponseType(typeof(ApiResult<UserDto>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<UserDto>> CreateUser([FromBody] CreateUserCommand command)
		{
			try
			{
				var data = await _mediator.Send(command);
				return new ApiResult<UserDto> { Code = ApiEnum.新增成功, Message = "创建成功", data = data };
			}
			catch (Exception ex)
			{
				return new ApiResult<UserDto> { Code = ApiEnum.新增失败, Message = ex.Message, data = null };
			}
		}

		/// <summary>
		/// 更新用户信息
		/// </summary>
		/// <param name="command">更新用户命令，包含用户ID和要更新的字段</param>
		/// <returns>更新后的用户信息</returns>
		/// <remarks>
		/// 示例请求:
		/// PUT /api/User/UpdateUser
		/// {
		///   "userId": 1,
		///   "email": "newemail@example.com",
		///   "fullName": "新名称",
		///   "phone": "13900139000",
		///   "isActive": true
		/// }
		/// </remarks>
		/// <response code="200">更新成功，返回更新后的用户信息</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">用户不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPut]
		[ProducesResponseType(typeof(ApiResult<UserDto>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<UserDto>> UpdateUser([FromBody] UpdateUserCommand command)
		{
			try
			{
				var data = await _mediator.Send(command);
				return new ApiResult<UserDto> { Code = ApiEnum.更新成功, Message = "更新成功", data = data };
			}
			catch (Exception ex)
			{
				return new ApiResult<UserDto> { Code = ApiEnum.更新失败, Message = ex.Message, data = null };
			}
		}

		/// <summary>
		/// 删除用户（逻辑删除）
		/// </summary>
		/// <param name="userId">用户ID</param>
		/// <returns>删除操作是否成功</returns>
		/// <remarks>
		/// 示例请求:
		/// DELETE /api/User/DeleteUser?userId=1
		/// 
		/// 注意：此操作是逻辑删除，不会真正删除数据库中的记录，只会标记为已删除状态。
		/// </remarks>
		/// <response code="200">删除成功</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">用户不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpDelete]
		[ProducesResponseType(typeof(ApiResult<bool>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<bool>> DeleteUser([FromQuery] long userId)
		{
			try
			{
				var ok = await _mediator.Send(new DeleteUserCommand { UserId = userId });
				return new ApiResult<bool> { Code = ApiEnum.删除成功, Message = "删除成功", data = ok };
			}
			catch (Exception ex)
			{
				return new ApiResult<bool> { Code = ApiEnum.删除失败, Message = ex.Message, data = false };
			}
		}

		/// <summary>
		/// 为用户分配角色（会覆盖原有角色）
		/// </summary>
		/// <param name="command">分配角色命令，包含用户ID和角色ID列表</param>
		/// <returns>分配操作是否成功</returns>
		/// <remarks>
		/// 示例请求:
		/// POST /api/User/AssignRoles
		/// {
		///   "userId": 1,
		///   "roleIds": [1, 2, 3]
		/// }
		/// 
		/// 注意：此操作会先删除用户原有的所有角色，然后分配新的角色。
		/// </remarks>
		/// <response code="200">分配成功</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">用户不存在或角色不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPost]
		[ProducesResponseType(typeof(ApiResult<bool>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<bool>> AssignRoles([FromBody] AssignRolesToUserCommand command)
		{
			try
			{
				var ok = await _mediator.Send(command);
				return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "分配成功", data = ok };
			}
			catch (Exception ex)
			{
				return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
			}
		}

		/// <summary>
		/// 修改用户密码（需要验证旧密码）
		/// </summary>
		/// <param name="command">修改密码命令，包含用户ID、旧密码和新密码</param>
		/// <returns>密码修改是否成功</returns>
		/// <remarks>
		/// 示例请求:
		/// POST /api/User/ChangePassword
		/// {
		///   "userId": 1,
		///   "oldPassword": "123456",
		///   "newPassword": "newpassword123"
		/// }
		/// 
		/// 注意：必须提供正确的旧密码才能修改密码。
		/// </remarks>
		/// <response code="200">密码修改成功</response>
		/// <response code="400">请求参数错误或旧密码错误</response>
		/// <response code="401">旧密码验证失败</response>
		/// <response code="404">用户不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPost]
		[ProducesResponseType(typeof(ApiResult<bool>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(401)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<bool>> ChangePassword([FromBody] ChangePasswordCommand command)
		{
			try
			{
				var ok = await _mediator.Send(command);
				return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "密码修改成功", data = ok };
			}
			catch (Exception ex)
			{
				return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
			}
		}
	}
}

